package com.webex.ta.hydra.gui.macro.action;

import com.webex.ta.hydra.Constants;
import com.webex.ta.hydra.core.macro.MacroDefinition;
import com.webex.ta.hydra.core.macro.MacroSerializer;
import com.webex.ta.hydra.gui.action.ActionHandler;
import com.webex.ta.hydra.gui.action.ActionNames;
import com.webex.ta.hydra.gui.macro.MacroEditorContext;
import com.webex.ta.hydra.gui.util.FileDialoger;
import org.apache.commons.io.FilenameUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-14
 * Time: 15:08:09
 */
public class MacroSaveAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.MACR0_SAVE);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        MacroEditorContext context = MacroEditorContext.getInstance();
        String updateFile = context.getMacroDefFile();
        if (updateFile == null) {
            JFileChooser chooser = FileDialoger.promptToSaveFile("" + Constants.HYDRA_MACRO_EXTENSION);
            if (chooser == null) {
                return;
            }
            updateFile = chooser.getSelectedFile().getAbsolutePath();
            // Make sure the file ends with proper extension
            if (FilenameUtils.getExtension(updateFile).equals("")) {
                updateFile = updateFile + Constants.HYDRA_MACRO_EXTENSION;
            }
            // Check if the user is trying to save to an existing file
            File f = new File(updateFile);
            if (f.exists()) {
                int response = JOptionPane.showConfirmDialog(context.getEditor(),
                        "The selected file already exists, do you want to overwrite it?",
                        "Save?",
                        JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.NO_OPTION) {
                    return; // Do not save, user does not want to overwrite
                }
            }
            context.setMacroDefFile(updateFile);
        }

        Vector<MacroDefinition> defs = context.getEditor().getMacroDefinitions();
        File f = new File(updateFile);
        try {
            OutputStream ostream = new FileOutputStream(f);
            MacroSerializer.saveMacroDefinitions(defs, ostream);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e1) {
            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
